/**
 * 路由字段验证中间件
 */
export default ({ headers, params, query, body }) => {
  const middleware = (req, res, next) => {
    let target = null
    let key = ''

    if (headers) {
      target = headers
      key = 'headers'
    } else if (params) {
      target = params
      key = 'params'
    } else if (query) {
      target = query
      key = 'query'
    } else {
      target = body
      key = 'body'
    }

    const result = target.safeParse(req[key])

    if (!result.success) {
      console.log(JSON.parse(result.error))
      // throw new Error(result.error)
      res.json({
        code: -1,
        data: null,
        message: result.error
      })

      return
    }

    next()
  }

  return middleware
}
